package online.yysh.charging.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

/**
 * 自动充满
 */
import androidx.annotation.NonNull;

import com.google.gson.Gson;
import online.yysh.charging.ChargingActivity;
import online.yysh.charging.R;
import online.yysh.charging.SelectChargingModeActivity;
import online.yysh.charging.base.BaseFragment;
import online.yysh.charging.bean.response.ErrorResponse;
import online.yysh.charging.bean.request.StartChargeRequest;
import online.yysh.charging.utils.HttpUtil;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AutoChargingFullFragment extends BaseFragment implements View.OnClickListener {
    private Button btn_startCharging;
    private String chargingData;

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_auto_charging, null);
        btn_startCharging = view.findViewById(R.id.btn_startCharging);
        btn_startCharging.setOnClickListener(this);
        return view;
    }

    @Override
    public void initData(Bundle savedInstanceState) {

    }

    @Override
    public void onAttach(@NonNull Activity activity) {
        super.onAttach(activity);
        chargingData = ((SelectChargingModeActivity)activity).getData();
    }

    @Override
    public void onClick(View view) {
        Toast.makeText(getActivity(),"开始充电",Toast.LENGTH_SHORT).show();
        startCharging();

    }

    private void startCharging(){
        String[] data = chargingData.split("_");
        int port = 0;
        if ("A".equals(data[1])){
            port = 65;
        }else{
            port = 66;
        }
        StartChargeRequest request = new StartChargeRequest(openid,data[0],port,1,0);
        HttpUtil.getInstance().startCharge(request, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                showToast("充电失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "startCharge:"+result );
                if (result.contains("ok")){
                    startActivity(new Intent(getActivity(), ChargingActivity.class).putExtra("isNewCharging",true));
                    getActivity().finish();
                }else{
                    ErrorResponse errorResponse = new Gson().fromJson(result,ErrorResponse.class);
                    showToast(errorResponse.getData());
                }
            }
        });
    }
}
